package main

import (
	"flag"
	"fmt"
	"log"
	"net/http"
	"os"
	"os/signal"
	"syscall"
)

func main() {
	// 定义命令行参数
	port := flag.Int("port", 8082, "HTTP服务器端口号")
	flag.Parse()

	// 设置验证处理程序
	http.HandleFunc("/validate", func(w http.ResponseWriter, r *http.Request) {
		// 获取查询参数
		appID := r.URL.Query().Get("appid")
		uid := r.URL.Query().Get("uid")
		token := r.URL.Query().Get("token")

		// 记录验证请求
		log.Printf("收到验证请求: appID=%s, uid=%s, token=%s", appID, uid, token)

		// 验证参数
		if appID == "" || uid == "" || token == "" {
			http.Error(w, "Missing required parameters", http.StatusBadRequest)
			return
		}

		// 根据不同的应用ID执行不同的验证逻辑
		var valid bool
		switch appID {
		case "app1":
			// app1: token必须是uid的反转
			valid = token == reverseString(uid)
		case "app2":
			// app2: token必须是"app2-"+uid
			valid = token == "app2-"+uid
		default:
			http.Error(w, "Unknown appID", http.StatusBadRequest)
			return
		}

		// 返回验证结果
		if valid {
			log.Printf("验证成功: appID=%s, uid=%s", appID, uid)
			w.WriteHeader(http.StatusOK)
			w.Write([]byte("Token is valid"))
		} else {
			log.Printf("验证失败: appID=%s, uid=%s, token=%s", appID, uid, token)
			http.Error(w, "Invalid token", http.StatusUnauthorized)
		}
	})

	// 创建HTTP服务器
	addr := fmt.Sprintf(":%d", *port)
	server := &http.Server{
		Addr: addr,
	}

	// 捕获系统信号，优雅关闭
	stop := make(chan os.Signal, 1)
	signal.Notify(stop, os.Interrupt, syscall.SIGTERM)

	// 启动HTTP服务器
	go func() {
		log.Printf("HTTP验证服务器启动在 http://localhost%s", addr)
		if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			log.Fatalf("Error starting server: %v", err)
		}
	}()

	// 等待中断信号
	<-stop
	log.Println("正在关闭服务器...")
	log.Println("服务器已退出")
}

// reverseString 反转字符串
func reverseString(s string) string {
	runes := []rune(s)
	for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
		runes[i], runes[j] = runes[j], runes[i]
	}
	return string(runes)
}
